package com.bmp.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.bmp.dao.ModuleDao;
import com.bmp.model.Module;
import com.bmp.model.vo.ProjectVoModule;
import com.bmp.util.HibernateUtil;

@Component("moduleDao")
public class ModuleDaoImpl implements ModuleDao {
	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void deleteModuleById(int id) {
		Module m = this.getModuleById(id);
		this.hibernateTemplate.delete(m);
	}

	public Module getModuleById(int id) {
		return (Module)this.hibernateTemplate.get(Module.class, id);
	}

	public void insertModule(Module m) {
		this.hibernateTemplate.save(m);
	}

	public void updateModule(Module m) {
		this.hibernateTemplate.update(m);
	}
	//获取每页显示的模块信息
	@SuppressWarnings("unchecked")
	public List<ProjectVoModule> getModule(int page, int rows) {
		List<ProjectVoModule> list = null;
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		String sql = "select new com.bmp.model.vo.ProjectVoModule(m.id,m.m_name,m.m_des,p.p_name) from Module m,Project p where m.pro_id = p.id order by m.id";
		list = session.createQuery(sql).setFirstResult((page-1)*rows).setMaxResults(rows).list();
		session.getTransaction().commit();
		return list;
	}
	//获取总记录数
	public int getTotalPages() {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		String sql = "select count(*) from Module m";
		long count = (Long)session.createQuery(sql).uniqueResult();
		session.getTransaction().commit();
		System.out.println(count);
		return (int)count;
	}

	public List<Module> getModuleByProId(int ProId) {
		List<Module> modules = this.hibernateTemplate.find("from Module m where m.pro_id = '"+ProId+"'");
		return modules;
	}

}
